<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function updateDOM() {
            console.log("更新视图");
        }

        //判断是不是对象，是对象继续递归
        function isObject(obj){
            return typeof obj === 'object' && obj !== null
        }

        function reactive(data) {
            //Proxy 对象用于创建一个对象的代理，从而实现基本操作的拦截和自定义（如属性查找、赋值、枚举、函数调用等）。
            return new Proxy(data, {
                //拦截读取
                get(target , property){
                    //读取属性之前判断是不是对象，是对象继续递归，创建为代理对象
                    const newObject = Reflect.get(target , property)
                    if(isObject(newObject)){
                        return reactive(newObject)
                    }
                    return newObject
                },
                //拦截修改
                set(target , property , value){
                    updateDOM()
                    return Reflect.set(target , property , value)
                },
                //拦截删除
                deleteProperty(target , property){
                    updateDOM()
                    return Reflect.deleteProperty(target , property)
                }
            })
        }

        //原始数据
        const data = {
            name: "laowang",
            age: 18,
            sex: "女",
            hobby: ["唱", "跳"],
            score: {
                math: 90,
                ch: 100,
            },
        };

        //调用reactive函数得到一个代理对象
        const proxyData = reactive(data)

        //读取
        console.log(proxyData.age);

        //修改
        proxyData.age = 19

        //删除
        delete proxyData.name

        //查看深层次对象也是代理对象
        console.log(proxyData.score);
        proxyData.score.ch = 1000

    </script>
</body>

</html>